package cn.itcast.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.itcast.model.Person;
import cn.itcast.service.PersonService;

@Controller
@RequestMapping("/person")
class PersonController {
	
	@Autowired
	PersonService personService;

	@RequestMapping("/savePerson.do")
	public String savePerson(Person person){
		personService.savePerson(person);
		return "redirect:getPersonByCondtion.do";
	}
	
	@RequestMapping("/preSave.do")
	public String preSave(Person person){
		return "add";
	}
	
	@RequestMapping("/updatePerson.do")
	public String updatePerson(Person person){
		personService.updatePerson(person);
		return "redirect:getPersonByCondtion.do";
	}
	@RequestMapping("/getPerson.do")
	public String getPerson(Integer personId, Model model){
		Person person = personService.getPerson(personId);
		model.addAttribute("person", person);
		return "update";
	}
	
	@RequestMapping("/getPersonByCondtion.do")
	public String getPersonByCondtion(String personName, Date birthday, String address, String gender, Model model){
		Map<String, Object> map = new HashMap<String , Object>();
		
		if(!"".equals(personName)){
			map.put("personName", personName);
		}
		if(!"".equals(address)){
			map.put("address", address);
		}
		
		map.put("birthday", birthday);
		if(!"2".equals(gender)){
			map.put("gender", gender);
		}
		
		List<Person> pList = personService.getPersonByCondtion(map);
		model.addAttribute("pList", pList);
		model.addAttribute("personName", personName);
		model.addAttribute("birthday", birthday);
		model.addAttribute("address", address);
		model.addAttribute("gender", gender);
		return "list";
	}
	
	@RequestMapping("/deletePerson.do")
	public String deletePerson(String ids){
		String [] idsArr = {};
		if(ids != null){
			idsArr = ids.split(",");
		}
		Map<String, Object> map = new HashMap<String , Object>();
		map.put("ids", idsArr);
		personService.deletePerson(map);
		return "redirect:getPersonByCondtion.do";
	}
	
	@InitBinder
	public void initBinder(ServletRequestDataBinder binder){
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}
}
